﻿using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;

namespace DbUp.ScriptProviders
{
    ///<summary>
    /// Provides a scripts from a list of files to be executed.
    ///</summary>
    public class FileEnumerationScriptProvider : IScriptProvider
    {
        private readonly List<SqlScript> _sqlScripts;

        ///<param name="scriptFiles">Enumeration of files that will be used as sql scripts</param>
        ///<exception cref="ArgumentNullException"></exception>
        public FileEnumerationScriptProvider(params FileInfo[] scriptFiles)
        {
            if (scriptFiles == null) throw new ArgumentNullException("scriptFiles");

            _sqlScripts = scriptFiles
                            .Select(s => new
                            {
                                Name = s.Name,
                                Contents = ReadFileContents(s)
                            })
                            .Select(s => new SqlScript(s.Name, s.Contents))
                            .ToList();

        }

        private static string ReadFileContents(FileInfo file)
        {
            using (var stream = file.OpenText())
            {
                return stream.ReadToEnd();
            }
        }


        public IEnumerable<SqlScript> GetScripts()
        {
            return _sqlScripts;
        }
    }

    public static class Extensions
    {
        //public static string SafelyTake<T>(IEnumerable<>)
    }
}